$(function() {
    var appTagPanel = $('#appTagPanel'),
		appTagListDiv = appTagPanel.find('ul:first'),

		appApiPanel = $('#appApiPanel'),
		appApiListDiv = appApiPanel.find('.panel-group'),
		appApiBrandDiv = appApiPanel.find('.navbar-brand'),
		appApiFuzzyInputDiv = appApiPanel.find('nav input'),
		appApiUsageBtn = appApiPanel.find('nav .input-group-btn:first button'),
		appApiSearchBtn = appApiPanel.find('nav .input-group-btn:last button'),
		appApiNewBtn = appApiPanel.find('nav button:last'),

		paginationDiv = $('#pagination'),

		appApiActionModal = $('#appApiActionModal'),
		appApiContentDiv = appApiActionModal.find('textarea'),
		appApiTitleDiv = appApiActionModal.find('input'),
		appApiEditor = undefined;

	var dataStorage = {
		appTagDivs: [],
		appVersionId: undefined,
		appApiDiv: undefined,
		page: {
			pagination: undefined,
			currentPage: 1,
			totalPages: 1
		},
		appApiUsage: 0,
		appApiActionMode: undefined
	};

	appTagListDiv.height($(window).height() - 220);
	$(window).resize(function() {
	    appTagListDiv.height(Math.max($(this).height() - 220, 330));
	});
	appApiListDiv.height($(window).height() - 270);
	$(window).resize(function() {
	    appApiListDiv.height(Math.max($(this).height() - 270, 280));
	});

	disableAppApiPanel(true);

	$.get(URLS.APP_TAG_BY_USAGE_VERSION_LIST(1))
	    .done(function(list) {
	        console.log(list);
	        $.each(list, function(i, appTag) {
	            var appTagDiv = $('<li>' +
					                '<label class="tree-toggle nav-header" style="cursor: pointer;">' + appTag.name + '</label>' +
					                	'<ul class="nav nav-list tree"></ul>' +
				                '</li>');
	            if (appTag.appVersions) {
		            $.each(appTag.appVersions, function(j, appVersion) {
		                appTagDiv.find('ul').append('<li><a style="cursor: pointer;" data-sid="' + appVersion.sid + '">V_' + appVersion.version + '</a></li>');
		            });
	            }
	            appTagListDiv.append(appTagDiv);
	            if (i < list.length - 1) {
	                appTagListDiv.append('<li class="nav-divider"></li>');
	            }
	            dataStorage.appTagDivs.push(appTagDiv);
	            blindVersionSelectEvent(appTagDiv);
	        });
	    })
	    .done(function() {
	        appTagPanel.find('.tree-toggle').click(function() {
	            $(this).parent().children('ul.tree').toggle(200);
	        });
	    });

	appTagPanel.find('input').on('keyup', function() {
	    var $this = $(this);
	    appTagListDiv.children().detach();
	    $.each(dataStorage.appTagDivs, function(i, appTagDiv) {
	        if (appTagDiv.find('label').text().toLowerCase().indexOf($this.val().toLowerCase()) != -1) {
	            appTagListDiv.append(appTagDiv);
	        }
	    });
	});

	appApiUsageBtn.on('click', function() {
		var $this = $(this);
		$this.removeClass('btn-default').addClass('btn-primary')
			 .siblings().removeClass('btn-primary').addClass('btn-default');
		dataStorage.appApiUsage = $this.data('usage');
		getApiPageByVersionIdAndUsage(dataStorage.appVersionId, dataStorage.appApiUsage);
	});

	appApiSearchBtn.on('click', function() {
		getApiPageByVersionIdAndUsage(dataStorage.appVersionId, dataStorage.appApiUsage, appApiFuzzyInputDiv.val());
	});

	appApiNewBtn.on('click', function() {
		appApiTitleDiv.val('');
		appApiEditor.html('');
		dataStorage.appApiActionMode = 'Add';
		appApiActionModal.modal('show');
	});

	// App API rich editor
	appApiEditor = appApiContentDiv.wangEditor();

	appApiActionModal.find('button:last').on('click', function() {
		if (appApiTitleDiv.val().length == 0 || appApiContentDiv.val().length == 0 || appApiContentDiv.val() === '<p><br></p>') {
			$.dfaceModal({
				title: '提示',
                content: 'Nothing about API',
                sizeClass: 'modal-sm',
                btns: ['确定']
			}).show();
			return;
		}
		if (dataStorage.appApiActionMode == 'Add') {
			$.post(URLS.APP_VERSION_BY_ID_API_ACTION_ADD(dataStorage.appVersionId), {
				title: appApiTitleDiv.val(),
				content: appApiContentDiv.val(),
				usage: dataStorage.appApiUsage
			}).done(function(result) {
				if (result.succeeded) {
					appApiActionModal.modal('hide');
					getApiPageByVersionIdAndUsage(dataStorage.appVersionId, dataStorage.appApiUsage);
				} else {
					appApiActionModal.find('.modal-body').prepend($.dfaceAlert('danger', '<strong>Error: </strong>' + (msg || 'Excute failed')));
				}
			});
		} else if (dataStorage.appApiActionMode == 'Edit') {
			$.post(URLS.APP_API_BY_ID(dataStorage.appApiDiv.data('sid')), {
				title: appApiTitleDiv.val(),
				content: appApiContentDiv.val()
			}).done(function(result) {
				if (result.succeeded) {
					appApiActionModal.modal('hide');
					dataStorage.appApiDiv.find('.panel-heading a[data-toggle]').text(result.obj.title);
					dataStorage.appApiDiv.find('.panel-body').html(result.obj.content);
				} else {
					appApiActionModal.find('.modal-body').prepend($.dfaceAlert('danger', '<strong>Error: </strong>' + (msg || 'Excute failed')));
				}
			});
		}
	});

	function blindVersionSelectEvent(appTagDiv) {
	    appTagDiv.find('a').on('click', function(e) {
	        e.preventDefault();
	        var $this = $(this);
	        dataStorage.appVersionId = $this.data('sid');
	        appApiBrandDiv.text(appTagDiv.find('label').text() + '#' + $this.text());
	        getApiPageByVersionIdAndUsage(dataStorage.appVersionId, dataStorage.appApiUsage);
	        disableAppApiPanel(false);
	    });
	}

	function disableAppApiPanel(disabled) {
		appApiUsageBtn.prop('disabled', disabled);
		appApiFuzzyInputDiv.prop('disabled', disabled);
		appApiSearchBtn.prop('disabled', disabled);
		appApiNewBtn.prop('disabled', disabled);
	}

	function getApiPageByVersionIdAndUsage(versionId, usage, fuzzyTitle) {
		appApiFuzzyInputDiv.val(fuzzyTitle);
	    $.get(URLS.APP_VERSION_BY_ID_API_BY_USAGE_PAGE(versionId, usage), {
	    	fuzzyTitle: fuzzyTitle,
	        pageNo: 1,
	        pageSize: GLOBAL_CONSTANT.PAGE_SIZE
	    }).done(function(pageResult) {
	        appApiListDiv.empty();
	        $.each(pageResult.objects, function(i, appApi) {
	            appApiListDiv.append(constructAppApiDiv(appApi));
	        });
	        if (dataStorage.page.pagination) {
	            dataStorage.page.pagination.data('twbs-pagination').destroy();
	        }
	        dataStorage.page.totalPages = pageResult.totalPages || 1,
	        dataStorage.page.pagination = paginationDiv.twbsPagination({
	            totalPages: dataStorage.page.totalPages,
	            visiblePages: 5,
	            initiateStartPageClick: false,
	            onPageClick: function(event, page) {
	            	dataStorage.page.currentPage = page;
	                $.get(URLS.APP_VERSION_BY_ID_API_PAGE(versionId), {
	                	fuzzyTitle: fuzzyTitle,
	                    pageNo: page,
	                    pageSize: GLOBAL_CONSTANT.PAGE_SIZE
	                }, function(pageResult) {
	                    appApiListDiv.empty();
	                    $.each(pageResult.objects, function(i, appApi) {
	                        appApiListDiv.append(constructAppApiDiv(appApi));
	                    });
	                });
	            }
	        });
	    });
	}

	function constructAppApiDiv(appApi) {
	 	var div = $('<div class="panel panel-default" data-sid="' + appApi.sid + '">' +
                        '<div class="panel-heading">' +
                            '<h4 class="panel-title pull-left" style="padding-top: 2px;">' +
                              '<a data-toggle="collapse" data-parent="#accordion" href="#appApi-' + appApi.sid + '">' + appApi.title + '</a>' +
                            '</h4>' +
                            '<div class="pull-right">' +
								'<a class="glyphicon glyphicon-edit" style="cursor: pointer; font-size: 1.2em; text-decoration: none; margin-right: 5px;"></a>' +
								'<a class="glyphicon glyphicon-trash" style="cursor: pointer; font-size: 1.2em; text-decoration: none; color: #A94442;"></a>' +
							'</div>' +
							'<div class="clearfix"></div>' +
                        '</div>' +
                        '<div id="appApi-' + appApi.sid + '" class="panel-collapse collapse">' +
                            '<div class="panel-body" style="height: 400px; overflow: auto;">' + appApi.content + '</div>' +
                        '</div>' +
                   	'</div>');
		blindApiEditEvent(div);
		blindApiDelEvent(div);
		return div;
	}

	function blindApiEditEvent(div) {
		div.find('.glyphicon-edit').on('click', function(e) {
			e.preventDefault();
			appApiTitleDiv.val(div.find('.panel-heading').text());
			appApiEditor.html(div.find('.panel-body').html());
			dataStorage.appApiActionMode = 'Edit';
			dataStorage.appApiDiv = div;
			appApiActionModal.modal('show');
		})
	}

	function blindApiDelEvent(div) {
		div.find('.glyphicon-trash').on('click', function(e) {
			e.preventDefault();
			var appApiDelModal = $.dfaceModal({
				title: 'Del API',
				content: '确定要删除API?',
				sizeClass: 'modal-sm',
				btns: ['取消', '确定']
			}).show();
			appApiDelModal.find('#btnOk').on('click', function() {
				$.ajax({
					url: URLS.APP_API_BY_ID(div.data('sid')),
					type: 'DELETE',
				}).done(function(result) {
					if (result.succeeded) {
						div.remove();
						updatePagination();
						appApiDelModal.modal('hide');
					} else {
						appApiDelModal.find('.modal-body').prepend($.dfaceAlert('danger', '<strong>Error: </strong>' + (msg || 'Excute failed')));
					}
				});
			});
		});
	}

	function updatePagination() {
	    return $.get(URLS.APP_VERSION_BY_ID_API_BY_USAGE_PAGE_COUNT(dataStorage.appVersionId, dataStorage.appApiUsage), {
	    	fuzzyTitle: appApiFuzzyInputDiv.val(),
	        pageSize: GLOBAL_CONSTANT.PAGE_SIZE
	    }, function(result) {
	        if (result != dataStorage.totalPages) {
	            dataStorage.page.totalPages = result || 1;
	            dataStorage.page.currentPage = Math.min(dataStorage.page.currentPage, dataStorage.page.totalPages);
	            dataStorage.page.pagination.data('twbs-pagination').updateTotalPages(dataStorage.page.currentPage, dataStorage.page.totalPages);
	        }
	    })
	}

});